package main

import (
	"fmt"
	cfg "github.com/go-kratos/kratos/contrib/config/etcd/v2"
	clientv3 "go.etcd.io/etcd/client/v3"
	"google.golang.org/grpc"
	"log"
	"time"
)

const testKey = "/kratos/test/config"

func main() {

	// new client
	client, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"127.0.0.1:2379"},
		DialTimeout: time.Second,
		DialOptions: []grpc.DialOption{grpc.WithBlock()},
	})
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		_ = client.Close()
	}()

	// new config
	source, err := cfg.New(client, cfg.WithPath(testKey), cfg.WithPrefix(true))
	if err != nil {
		log.Fatal(err)
	}

	// put
	//if _, err = client.Put(context.Background(), testKey, "test config"); err != nil {
	//	log.Fatal(err)
	//}

	// load
	//kvs, err := source.Load()
	//if err != nil {
	//	log.Fatal(err)
	//}

	//if len(kvs) != 1 || kvs[0].Key != testKey || string(kvs[0].Value) != "test config" {
	//	log.Fatal("config error")
	//}

	// Notice watch
	w, err := source.Watch()
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		_ = w.Stop()
	}()

	// 死循环监听～
	for {
		kvs, err := w.Next()
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(">>> ", kvs[0].Key, string(kvs[0].Value))
	}

}
